//
//  HttpRequestManager.m
//  hospitalUser
//
//  Created by 888 on 2021/10/9.
//

#import "HttpRequestManager.h"
#import "Safety.h"
#import <sys/utsname.h>
#import "AnalysisHandle.h"
#define DEFAULT_REQUEST_TIME_OUT 20

typedef NS_ENUM(NSUInteger, HTTPMethod) {
    GET,
    POST
};


@interface HttpRequestManager ()
@property (strong,nonatomic) AFHTTPSessionManager *manager;
@end



@implementation HttpRequestManager

- (id)copyWithZone:(NSZone *)zone {
    return [[HttpRequestManager allocWithZone:zone] init];
}

+ (id)allocWithZone:(NSZone *)zone{
    return [self sharedDefaultManager];
}

+ (instancetype)sharedDefaultManager{
  static dispatch_once_t onceToken;
  static HttpRequestManager *manager = nil;
  dispatch_once(&onceToken, ^{
      manager = [[super allocWithZone:NULL] init];
  });
  return manager;
}

-(AFHTTPSessionManager*)manager{
    if (!_manager) {
        NSString *url = [self matchingAppServerUrl];
        _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
        _manager.requestSerializer.timeoutInterval = DEFAULT_REQUEST_TIME_OUT;
        _manager.securityPolicy.allowInvalidCertificates = YES;
    }
    return _manager;
}


- (BOOL)isNetSuccess:(id)JSON{

    id codeStr = [JSON objectForKey:@"code"];
    if (codeStr == nil) {
        return NO;
    }
    int code = [codeStr intValue];
    BOOL bSuccess = NO;
    if (code == 200) {
        bSuccess = YES;
    }else{
        return NO;
    }
    return bSuccess;
}

- (NSString *)getCommentErrorString:(NSError *)error{
    NSString *msg = @"网络异常,请检查网络";
    if (error.code == NSURLErrorTimedOut) {
        msg = @"请求超时,请检查网络";
    }
    else if (error.code == NSURLErrorCannotConnectToHost || error.code == NSURLErrorNotConnectedToInternet) {
        msg = @"网络未开启,请检查网络";
    }else if([error code] == NSURLErrorCancelled){
        msg = @"请检查网络,已经取消";
    }
    return msg;
}


- (NSMutableDictionary*)getRequestHeader{
  //添加header
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters SafetySetObject:[self getAppVersion] forKey:@"appVersion"];
    [parameters SafetySetObject:@"iOS" forKey:@"phoneType"];
    [parameters SafetySetObject:@"GYTJK" forKey:@"platform"];
    [parameters SafetySetObject:[self getDeviceId] forKey:@"serialNumber"];
    NSString * development  = [AnalysisHandle instanceHandle].developmentUrl;
    if ([development isEqual:@"pre-release"]){
       [parameters SafetySetObject:@"pre" forKey:@"Juse-Version"];
    }
    return parameters;
}


//PSOT 请求
- (void)requestPostWithPath:(NSString *)path params:(NSMutableDictionary *)params completed:(HttpCompletedBlock)completed{
    [self requestWithMetod:POST path:path params:params completed:completed];
}

//GET请求
- (void)requestGetWithPath:(NSString *)path params:(NSMutableDictionary *)params completed:(HttpCompletedBlock)completed{
    [self requestWithMetod:GET path:path params:params completed:completed];
}


- (void)requestWithMetod:(HTTPMethod)method path:(NSString *)path params:(NSDictionary *)params completed:(HttpCompletedBlock)completed{
  
    switch (method) {
        case GET: {
          [[self manager]GET:path parameters:params headers:[self getRequestHeader] progress:^(NSProgress * _Nonnull downloadProgress) {
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
 
           BOOL bSuccess = [self isNetSuccess:responseObject];
           if (bSuccess) {
                completed(YES, responseObject);
           }else{
                completed(NO, responseObject[@"mes"]);
           }
           
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           NSString *errStr = [self getCommentErrorString:error];
           if (completed) {
               completed(NO, errStr);
           }
        }];
            break;
        }
            
        case POST: {
          
          //使用苹果自带的类NSJSONSerialization生成json
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
          NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
          NSString *urlString = [NSString stringWithFormat:@"%@%@",[self matchingAppServerUrl],path];
          NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
          [request setHTTPMethod:@"POST"];
          [request setHTTPBody:tempJsonData];
          NSLog(@"请求参数=====%@",request.HTTPBody);
           //添加header
          NSMutableURLRequest *mutableRequest = [request mutableCopy];    //拷贝request
          [mutableRequest addValue:@"application/json" forHTTPHeaderField:@"Accept"];
          [mutableRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
          [mutableRequest addValue:[self getAppVersion] forHTTPHeaderField:@"version"];
          [mutableRequest addValue:@"GYTJK" forHTTPHeaderField:@"platform"];
          [mutableRequest addValue:@"iOS" forHTTPHeaderField:@"phoneType"];
          NSString * development  = [AnalysisHandle instanceHandle].developmentUrl;
          if ([development isEqual:@"pre-release"]){
              [mutableRequest addValue:@"pre" forHTTPHeaderField:@"Juse-Version"];
          }
          request = [mutableRequest copy];
          NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
              if (error) {
                NSLog(@"请求error=====%@",error.userInfo);
                NSString *errStr = [self getCommentErrorString:error];
                if (completed) {
                    completed(NO, errStr);
                }
              } else {
                if (completed) {
                  NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                  completed(YES,responseObject);
                }
               
              }
          }];
          
          [dataTask resume];
            break;
        }
        default: {
            break;
        }
    }
}



- (NSString *) getAppVersion {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

- (NSString *) getDeviceId {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* deviceId = [NSString stringWithCString:systemInfo.machine
                                    encoding:NSUTF8StringEncoding];
    #if TARGET_IPHONE_SIMULATOR
        deviceId = [NSString stringWithFormat:@"%s", getenv("SIMULATOR_MODEL_IDENTIFIER")];
    #endif
    return deviceId;
}


- (NSString *)matchingAppServerUrl{
  
   NSString * development  = [AnalysisHandle instanceHandle].developmentUrl;
   NSString *BASE_API_URL;
  
  if([development isEqual:@"development"]){
      BASE_API_URL = BASE_API_URL_DEV;
  }else  if([development isEqual:@"testing"]){
    BASE_API_URL =  BASE_API_URL_TEST;
  }else{
      BASE_API_URL = BASE_API_URL_Release;
  }
  return BASE_API_URL;
}


@end
